<template>
  <view class="container">
    <!-- 用户信息卡片 -->
    <view class="user-card">
      <view class="user-header">
        <button 
          class="avatar-wrapper"
          open-type="chooseAvatar"
          @chooseavatar="onChooseAvatar"
        >
          <image 
            class="user-avatar" 
            :src="userInfo.wechatAvatar || '/static/default-avatar.png'" 
            mode="aspectFill"
          ></image>
        </button>
        <view class="user-info">
          <input 
            class="user-name-input"
            type="nickname"
            v-model="editingNickname"
            :placeholder="userInfo.wechatNickname || userInfo.nickName || '微信用户'"
            @blur="onNicknameBlur"
            @confirm="onNicknameConfirm"
          />
          <text class="user-type">{{ getUserTypeText() }}</text>
        </view>
        <view class="user-status">
          <text class="status-text">已登录</text>
        </view>
      </view>
      
      <view class="user-details">
        <view class="detail-item" v-if="userInfo.wechatGender">
          <text class="detail-label">性别：</text>
          <text class="detail-value">{{ getGenderText() }}</text>
        </view>
        <view class="detail-item" v-if="userInfo.wechatProvince || userInfo.wechatCity">
          <text class="detail-label">地区：</text>
          <text class="detail-value">{{ getLocationText() }}</text>
        </view>
        <view class="detail-item" v-if="userInfo.wechatCountry">
          <text class="detail-label">国家：</text>
          <text class="detail-value">{{ userInfo.wechatCountry }}</text>
        </view>
        <view class="detail-item">
          <text class="detail-label">用户名：</text>
          <text class="detail-value">{{ userInfo.userName }}</text>
        </view>
        <view class="detail-item" v-if="userInfo.lastLoginTime">
          <text class="detail-label">最后登录：</text>
          <text class="detail-value">{{ formatDate(userInfo.lastLoginTime) }}</text>
        </view>
        <view class="detail-item" v-if="userInfo.loginCount">
          <text class="detail-label">登录次数：</text>
          <text class="detail-value">{{ userInfo.loginCount }} 次</text>
        </view>
      </view>
    </view>

    <!-- 功能菜单 -->
    <view class="menu-section">
      <view class="section-title">功能菜单</view>
      
      <view class="menu-list">
        <view class="menu-item" @click="refreshUserInfo">
          <view class="menu-icon">🔄</view>
          <text class="menu-text">刷新信息</text>
          <text class="menu-arrow">></text>
        </view>
        
        <view class="menu-item" @click="viewMyFeedback">
          <view class="menu-icon">📝</view>
          <text class="menu-text">我的反馈</text>
          <text class="menu-arrow">></text>
        </view>
        
        <view class="menu-item" @click="viewMyWork">
          <view class="menu-icon">🎯</view>
          <text class="menu-text">我的工作</text>
          <text class="menu-arrow">></text>
        </view>
      </view>
    </view>

    <!-- 系统信息 -->
    <view class="system-section">
      <view class="section-title">系统信息</view>
      
      <view class="info-list">
        <view class="info-item">
          <text class="info-label">应用版本：</text>
          <text class="info-value">v1.0.0</text>
        </view>
        <view class="info-item">
          <text class="info-label">登录时间：</text>
          <text class="info-value">{{ formatDate(new Date()) }}</text>
        </view>
      </view>
    </view>

    <!-- 退出登录按钮 -->
    <view class="logout-section">
      <button class="logout-btn" @click="handleLogout">退出登录</button>
    </view>
  </view>
</template>

<script>
import authService from '@/utils/auth.js'
import { uploadApi } from '@/utils/api-simple.js'
import { config } from '@/config/api.js'

export default {
  data() {
    return {
      userInfo: {},
      loading: false,
      editingNickname: '',  // 正在编辑的昵称
      avatarUploading: false
    }
  },
  
  onLoad() {
    // 检查登录状态
    this.checkAuthAndLoad()
  },
  
  onShow() {
    // tab切换时检查登录状态并刷新用户信息
    console.log('我的页面显示，检查登录状态')
    // 如果未登录，跳转到登录页面；如果已登录，刷新用户信息
    if (!authService.isLoggedIn()) {
      uni.redirectTo({
        url: '/pages/login/login?from=/pages/profile/profile'
      })
      return
    }
    this.loadUserInfo()
  },
  
  methods: {
    // 检查认证并加载数据
    checkAuthAndLoad() {
      // 检查是否已登录
      if (!authService.isLoggedIn()) {
        // 未登录，跳转到登录页面，并传递来源页面信息
        uni.redirectTo({
          url: '/pages/login/login?from=/pages/profile/profile'
        })
        return
      }
      // 已登录，加载用户信息
      this.loadUserInfo()
    },
    
    // 加载用户信息
    loadUserInfo() {
      try {
        const userInfo = authService.getUserInfo()
        if (userInfo) {
          this.userInfo = userInfo
          console.log('用户信息:', userInfo)
        } else {
          console.log('未找到用户信息')
          // 未找到用户信息时跳转到登录页面
          uni.redirectTo({
            url: '/pages/login/login?from=/pages/profile/profile'
          })
        }
      } catch (error) {
        console.error('加载用户信息失败:', error)
        uni.showToast({
          title: '加载用户信息失败',
          icon: 'none'
        })
      }
    },
    
    // 获取用户类型文本
    getUserTypeText() {
      if (this.userInfo.userType === '01') {
        return '微信用户'
      } else if (this.userInfo.userType === '00') {
        return '系统用户'
      }
      return '普通用户'
    },
    
    // 获取性别文本
    getGenderText() {
      const gender = this.userInfo.wechatGender
      if (gender === '1') {
        return '男'
      } else if (gender === '2') {
        return '女'
      }
      return '未知'
    },
    
    // 获取地区文本
    getLocationText() {
      const province = this.userInfo.wechatProvince || ''
      const city = this.userInfo.wechatCity || ''
      
      if (province && city) {
        return `${province} ${city}`
      } else if (province) {
        return province
      } else if (city) {
        return city
      }
      return '未知'
    },
    
    // 格式化日期
    formatDate(date) {
      if (!date) return '未知'
      
      const d = new Date(date)
      const year = d.getFullYear()
      const month = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      const hours = String(d.getHours()).padStart(2, '0')
      const minutes = String(d.getMinutes()).padStart(2, '0')
      
      return `${year}-${month}-${day} ${hours}:${minutes}`
    },
    
    // 刷新用户信息（重新从后端加载）
    async refreshUserInfo() {
      try {
        uni.showLoading({
          title: '刷新中...',
          mask: true
        })
        
        // 重新加载用户信息
        this.loadUserInfo()
        
        uni.hideLoading()
        uni.showToast({
          title: '刷新成功',
          icon: 'success'
        })
      } catch (error) {
        uni.hideLoading()
        console.error('刷新用户信息失败:', error)
        uni.showToast({
          title: '刷新失败',
          icon: 'none',
          duration: 2000
        })
      }
    },
    
    // 选择头像
    async onChooseAvatar(e) {
      const tempPath = e.detail.avatarUrl
      console.log('选择头像:', tempPath)
      if (!tempPath || this.avatarUploading) {
        return
      }
      
      if (this.userInfo) {
        this.userInfo.wechatAvatar = tempPath
      }
      this.avatarUploading = true
      
      try {
        const remoteUrl = await this.uploadAvatarFile(tempPath)
        if (!remoteUrl) {
          throw new Error('未获取到远程地址')
        }
        if (this.userInfo) {
          this.userInfo.wechatAvatar = remoteUrl
        }
        await authService.saveUserAvatar(remoteUrl)
        uni.showToast({
          title: '头像已更新',
          icon: 'success',
          duration: 1500
        })
        this.loadUserInfo()
      } catch (error) {
        console.error('保存头像失败:', error)
        uni.showToast({
          title: '头像上传失败，请重试',
          icon: 'none',
          duration: 2000
        })
      } finally {
        this.avatarUploading = false
      }
    },
    
    // 昵称输入失焦
    onNicknameBlur(e) {
      const value = e.detail.value || e.target.value
      if (value && value.trim()) {
        this.editingNickname = value.trim()
        this.saveNickname(value.trim())
      }
    },
    
    // 昵称输入确认
    onNicknameConfirm(e) {
      const value = e.detail.value || e.target.value
      if (value && value.trim()) {
        this.editingNickname = value.trim()
        this.saveNickname(value.trim())
      }
    },
    
    // 保存昵称
    async saveNickname(nickname) {
      if (!nickname || !nickname.trim()) {
        return
      }
      
      try {
        // 更新本地显示
        if (this.userInfo) {
          this.userInfo.wechatNickname = nickname.trim()
        }
        
        // 保存到后端
        await authService.saveUserNickname(nickname.trim())
        
        uni.showToast({
          title: '昵称已更新',
          icon: 'success',
          duration: 1500
        })
        
        // 重新加载用户信息以确保同步
        this.loadUserInfo()
      } catch (error) {
        console.error('保存昵称失败:', error)
        uni.showToast({
          title: '保存失败，请重试',
          icon: 'none',
          duration: 2000
        })
      }
    },
    
    
    // 查看我的反馈
    viewMyFeedback() {
      uni.showModal({
        title: '我的反馈',
        content: '此功能正在开发中，敬请期待！',
        showCancel: false,
        confirmText: '我知道了'
      })
    },
    
    // 查看我的工作
    viewMyWork() {
      uni.showModal({
        title: '我的工作',
        content: '此功能正在开发中，敬请期待！',
        showCancel: false,
        confirmText: '我知道了'
      })
    },
    
    // 退出登录
    handleLogout() {
      uni.showModal({
        title: '退出登录',
        content: '确定要退出登录吗？',
        success: (res) => {
          if (res.confirm) {
            authService.logout()
            uni.showToast({
              title: '已退出登录',
              icon: 'success'
            })
            
            // 跳转到登录页面
            setTimeout(() => {
              uni.redirectTo({
                url: '/pages/login/login'
              })
            }, 1500)
          }
        }
      })
    },
    
    isRemoteUrl(url) {
      if (!url) return false
      const lower = url.toLowerCase()
      if (lower.startsWith('wxfile://')) return false
      if (lower.startsWith('http://tmp') || lower.startsWith('https://tmp') || lower.startsWith('//tmp')) {
        return false
      }
      return /^https?:\/\//.test(lower)
    },
    
    normalizeUploadUrl(result) {
      if (!result) return ''
      const directUrl = result.url || result.data?.url || result.data?.fileUrl
      if (directUrl) {
        return directUrl
      }
      const fileName = result.fileName || result.data?.fileName
      if (fileName) {
        if (this.isRemoteUrl(fileName)) {
          return fileName
        }
        const base = config.BASE_URL || ''
        if (!base) return fileName
        if (fileName.startsWith('/')) {
          return `${base}${fileName}`
        }
        return `${base}/${fileName}`
      }
      return ''
    },
    
    async uploadAvatarFile(filePath) {
      if (!filePath) return ''
      if (this.isRemoteUrl(filePath)) {
        return filePath
      }
      const result = await uploadApi.uploadImage(filePath)
      return this.normalizeUploadUrl(result)
    }
  }
}
</script>

<style scoped>
.container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 用户信息卡片 */
.user-card {
  background-color: white;
  border-radius: 20rpx;
  padding: 40rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.user-header {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}

.avatar-wrapper {
  background: transparent;
  border: none;
  padding: 0;
  margin: 0;
  margin-right: 30rpx;
  line-height: 1;
}

.avatar-wrapper::after {
  border: none;
}

.user-avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 60rpx;
  border: 4rpx solid #4CAF50;
}

.user-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.user-name-input {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
  padding: 0;
  background: transparent;
  border: none;
  line-height: 1.2;
}

.user-name {
  display: block;
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.user-type {
  display: block;
  font-size: 24rpx;
  color: #4CAF50;
  background-color: #e8f5e8;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  width: fit-content;
}

.user-status {
  text-align: right;
}

.status-text {
  font-size: 24rpx;
  color: #4CAF50;
  background-color: #e8f5e8;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
}

.user-details {
  border-top: 1rpx solid #eee;
  padding-top: 30rpx;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.detail-item:last-child {
  border-bottom: none;
}

.detail-label {
  font-size: 28rpx;
  color: #666;
}

.detail-value {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

/* 功能菜单 */
.menu-section {
  margin-bottom: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  padding-left: 10rpx;
  border-left: 6rpx solid #4CAF50;
}

.menu-list {
  background-color: white;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 30rpx 40rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.menu-item:last-child {
  border-bottom: none;
}

.menu-item:active {
  background-color: #f5f5f5;
}

.menu-icon {
  font-size: 40rpx;
  margin-right: 30rpx;
  width: 40rpx;
  text-align: center;
}

.menu-text {
  flex: 1;
  font-size: 30rpx;
  color: #333;
}

.menu-arrow {
  font-size: 24rpx;
  color: #999;
}

/* 系统信息 */
.system-section {
  margin-bottom: 30rpx;
}

.info-list {
  background-color: white;
  border-radius: 20rpx;
  padding: 30rpx 40rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.info-label {
  font-size: 28rpx;
  color: #666;
}

.info-value {
  font-size: 28rpx;
  color: #333;
}

/* 退出登录 */
.logout-section {
  margin-top: 60rpx;
}

.logout-btn {
  width: 100%;
  height: 88rpx;
  background-color: #f44336;
  color: white;
  border-radius: 44rpx;
  font-size: 32rpx;
  font-weight: bold;
  border: none;
  box-shadow: 0 4rpx 20rpx rgba(244, 67, 54, 0.3);
}

.logout-btn:active {
  background-color: #d32f2f;
  transform: translateY(2rpx);
}
</style>
